package cn.tedu.knows.portal.controller;


import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.model.Answer;
import cn.tedu.knows.portal.service.IAnswerService;
import cn.tedu.knows.portal.vo.AnswerVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-10-27
 */
@RestController
@RequestMapping("/v1/answers")
@Slf4j
public class AnswerController {

    @Autowired
    private IAnswerService answerService;

    @PostMapping("")
    //@PreAuthorize("hasAuthority('/question/answer')")
    // hasRole是特指验证角色的指令
    // ROLE_开头的auth就是角色的标识
    // hasRole验证时可以将ROLE_省略直接写它后面的内容
    // 但是它的判断也不死板hasRole('ROLE_TEACHER')也可以
    @PreAuthorize("hasRole('TEACHER')")
    public Answer postAnswer(
            @Validated AnswerVo answerVo,
            BindingResult result,
            @AuthenticationPrincipal UserDetails user){
        log.debug("表单信息:{}",answerVo);
        if(result.hasErrors()){
            String msg=result.getFieldError()
                                    .getDefaultMessage();
            throw new ServiceException(msg);
        }
        //这里调用业务逻辑层方法
        Answer answer=answerService
                    .saveAnswer(answerVo,user.getUsername());
        return answer;
    }



    // /v1/answers/question/149
    @GetMapping("/question/{id}")
    public List<Answer> questionAnswers(
            @PathVariable Integer id){
        List<Answer> answers=answerService
                        .getAnswersByQuestionId(id);
        return answers;
    }

    // 采纳回答的控制层代码
    // localhost:8080/v1/answers/83/solved
    @GetMapping("/{answerId}/solved")
    public String solved(
            @PathVariable Integer answerId,
            @AuthenticationPrincipal UserDetails user){
        boolean accepted=answerService.accept(
                            answerId,user.getUsername());
        if(accepted){
            return "ok";
        }else{
            return "必须是问题的提问者才能采纳回答";
        }
    }


}






